<?php
/**
 * Created by JetBrains PhpStorm.
 * User: thanhdx
 * Date: 19/04/2012
 * Time: 22:55
 * To change this template use File | Settings | File Templates.
 */
class ChangePassForm extends CFormModel
{
    public $old_password;
    public $new_password;
    public $confirm_new_password;

    public function rules(){
        return array(
            array('old_password,new_password','required'),
            array('old_password','checkPass'),
            array('new_password','length','min'=>6),
            array('confirm_new_password','compare','compareAttribute'=>'new_password'),
        );
    }

    public function checkPass($attribute,$params){
        /**
         * @var $user User
         */
        $user = User::model()->findByPk(Yii::app()->user->id);
        if($user->password != $user->hashPassword($this->old_password)){
            $this->addError('old_password','Bạn đã nhập sai mật khẩu cũ!');
        }
    }

    public function save(){
        /**
         * @var $user User
         *
         */
        $user = User::model()->findByPk(Yii::app()->user->id);
        $user->password = $user->hashPassword(trim($this->new_password));
        return $user->update('password');
    }

    public function attributeLabels(){
        return array(
            'old_password'=>'Mật khẩu hiện tại',
            'new_password'=>'Mật khẩu mới',
            'confirm_new_password'=>'Nhập lại mật khẩu mới',
        );
    }
}
